import bpy
import re
from uuid import uuid4
from bpy.types import Operator
from ...addon.naming import FluidLabNaming
from bpy.props import StringProperty, EnumProperty
from ...libs.functions.get_common_vars import get_common_vars
from ...libs.functions.collections import set_active_collection_to_master_coll, create_new_collection, set_active_collection_by_name
from ...libs.functions.object import name_with_zfill


class FLUIDLAB_OT_fluid_group_list_add(Operator):
    bl_idname = "fluidlab.fluid_group_list_add"
    bl_label = "Add New Group"
    bl_description = "Add Group to Fluid Groups List"
    bl_options = {"REGISTER", "UNDO"}

    emitter_type: EnumProperty(
        items=[
            ('GEOMETRY',    "Geometry", "", 0),
            ('INFLOW',      "InFlow",   "", 1),
        ],
        default='GEOMETRY'
    )

    group_name: StringProperty(
                                name="Name",
                                description="Group Name",
                                default=""
                            )


    def execute(self, context):

        if not self.group_name:
            self.report({'ERROR'}, "Invalid Name!")
            return {'CANCELLED'}

        fluid_groups = get_common_vars(context, get_fluid_groups=True)

        # Si no existe se crea y se deja activa FluidLab:
        set_active_collection_to_master_coll(context)
        
        id_name = str(uuid4())[:6]
        place = bpy.data.collections
        desired_name = FluidLabNaming.GROUP_PREFIX + self.group_name.title()
        label_txt = name_with_zfill(context, desired_name, place)

        # Intermediate collection Fluid_Goups:
        inter_coll = bpy.data.collections.get(FluidLabNaming.FLUID_GROUPS_COLL)
        if not inter_coll:
            inter_coll = create_new_collection(context, FluidLabNaming.FLUID_GROUPS_COLL)
        
        # Marcamos la collection como de tipo FluidLab_coll (para poder filtralas mejor):
        inter_coll[FluidLabNaming.FluidLab] = True
        set_active_collection_by_name(context, inter_coll.name)

        # Group collection:
        new_coll = bpy.data.collections.get(label_txt)
        if not new_coll:
            new_coll = create_new_collection(context, label_txt, False)

        # Marcamos la collection como de tipo FluidLab_coll (para poder filtralas mejor):
        new_coll[FluidLabNaming.FluidLab] = True
        new_coll[FluidLabNaming._GROUPS_COLL] = True
        fluid_groups.add_item(id_name, label_txt, new_coll, self.emitter_type)

        return {'FINISHED'}

    def invoke(self, context, event):
        
        # Sugiero el nombre de algún objeto de tipo mesh valido:        
        if context.selected_objects:
            ob = next((ob for ob in reversed(context.selected_objects) if ob.type == 'MESH' and ob.visible_get()), None)
            if ob:
                
                # Procuro evitar pillar nombres con .001 etc, me quedo solo con el nombre:
                regex = "(.*)(\.[0-9]+)"
                match = re.search(regex, ob.name)
                if match:
                    self.group_name = match.group(1)
                else:
                    self.group_name = ob.name

        return context.window_manager.invoke_props_dialog(self, width=200)

    def draw(self, context):
        
        layout = self.layout
        layout.use_property_decorate = False
        layout.use_property_split = False
        
        group_name = layout.column(align=True)
        if len(self.group_name) <= 0:
            group_name.alert = True
        group_name.prop(self, "group_name")
        
        types = layout.row(align=True)
        types.scale_y = 1.3
        types.prop(self, "emitter_type", expand=True)

